# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger

__all__ = ['FSRRabbitmqQueue']

class FSRRabbitmqQueue(Base, SessionMixin):
    '''
    Rabbitmq队列堵塞，自动扩容消费者
    '''
    __tablename__ = "fsr_rabbitmq_queue"
    name = Column(String(256), nullable=False, index=True, comment='队列名称')
    vhost = Column(String(256), nullable=False, index=True, comment='虚拟主机')
    cluster = Column(String(256), nullable=False, index=True, comment='集群名称')
    consumer = Column(String(256), nullable=False, comment='消费者服务名称')
    # deployment or statefulset
    classes = Column(String(128), nullable=False, index=True, comment='消费者服务部署归类')
    # firing / resolved
    status = Column(String(16), default="resolved", index=True, comment='告警状态')
    # true/false
    state = Column(Boolean, default=text('true'), comment='使能状态')
    # true/false
    handle = Column(Boolean, default=text('False'), comment='是否操作扩容')
    number = Column(Integer, nullable=True, comment='扩容前节点数')
    max = Column(Integer, nullable=False, comment='服务最大节点数')
    update_at = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    comment = Column(String(256), nullable=True, comment='队列说明')


    __table_args__ = (
        Index('idx_fsr_rabbitmq_queue_cluster_vhost_name', 'cluster', 'vhost', 'name', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<fsr_rabbitmq_queue={self.name}>"

    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }

        return result



    @classmethod
    def get_object_by_cluster_vhost_name(cls, db: Session, cluster: str, vhost: str, name: str):
        """
        根据集群名称/虚拟主机/队列名称，查找是否存在
        """
        # 优先
        object = db.query(cls).filter(
            cls.cluster == cluster,
            cls.vhost == vhost,
            cls.name == name
        ).first()

        return object

